{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c990fed8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "query_history_k_data_plus respond error_code:0\n",
      "query_history_k_data_plus respond  error_msg:success\n",
      "Empty DataFrame\n",
      "Columns: [date, code, open, high, low, close, preclose, volume, amount, adjustflag, turn, tradestatus, pctChg, isST]\n",
      "Index: []\n",
      "logout success!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<baostock.data.resultset.ResultData at 0x1d91dcdb460>"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 抓取股票数据\n",
    "import baostock as bs\n",
    "import pandas as pd\n",
    "#### 登陆系统 ####\n",
    "lg = bs.login()\n",
    "\n",
    "rs = bs.query_history_k_data_plus(\"sz.159915\",\n",
    "    \"date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST\",\n",
    "    start_date='2020-01-01', end_date='2020-12-31',\n",
    "    frequency=\"d\", adjustflag=\"3\")\n",
    "print('query_history_k_data_plus respond error_code:'+rs.error_code)\n",
    "print('query_history_k_data_plus respond  error_msg:'+rs.error_msg)\n",
    "#### 打印结果集 ####\n",
    "data_list = []\n",
    "while (rs.error_code == '0') & rs.next():\n",
    "    # 获取一条记录，将记录合并在一起\n",
    "    data_list.append(rs.get_row_data())\n",
    "result = pd.DataFrame(data_list, columns=rs.fields)\n",
    "\n",
    "#### 结果集输出到csv文件 ####   \n",
    "result.to_csv(\"D:\\\\history_A_stock_k_data.csv\", index=False)\n",
    "print(result)\n",
    "\n",
    "#### 登出系统 ####\n",
    "bs.logout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f2221d46",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "login respond error_code:0\n",
      "login respond  error_msg:success\n",
      "query_history_k_data_plus respond error_code:0\n",
      "query_history_k_data_plus respond  error_msg:success\n",
      "            date       code       open       high        low      close  \\\n",
      "0     2010-06-01  sz.399006   986.0156   994.7931   948.1186   973.2333   \n",
      "1     2010-06-02  sz.399006   967.6097   997.1196   952.6116   997.1196   \n",
      "2     2010-06-03  sz.399006  1002.3550  1026.7020   997.7751   998.3949   \n",
      "3     2010-06-04  sz.399006   989.6815  1027.6820   986.5043  1027.6820   \n",
      "4     2010-06-07  sz.399006  1005.0290  1075.2250  1001.7030  1069.4690   \n",
      "...          ...        ...        ...        ...        ...        ...   \n",
      "2627  2021-03-24  sz.399006  2650.3724  2678.4021  2623.2924  2634.6142   \n",
      "2628  2021-03-25  sz.399006  2609.3782  2670.8964  2603.9371  2655.9988   \n",
      "2629  2021-03-26  sz.399006  2672.9087  2754.3027  2672.9087  2745.4001   \n",
      "2630  2021-03-29  sz.399006  2747.8562  2768.1403  2716.9466  2733.9632   \n",
      "2631  2021-03-30  sz.399006  2728.4902  2779.8660  2722.2340  2771.3221   \n",
      "\n",
      "       preclose      volume             amount     pctChg  \n",
      "0        0.0000   135628510    4924176838.9100   0.000000  \n",
      "1      973.2333   107462758    4001206160.7700   2.454330  \n",
      "2      997.1196   161680539    6240835495.9000   0.127895  \n",
      "3      998.3949   150029501    5269440644.1100   2.933383  \n",
      "4     1027.6820   265527537    9106094723.4200   4.066141  \n",
      "...         ...         ...                ...        ...  \n",
      "2627  2668.0818  8087879483  138866686488.8400  -1.254369  \n",
      "2628  2634.6142  8474103400  139611833473.9200   0.811679  \n",
      "2629  2655.9988  8065214991  149296519930.4900   3.366014  \n",
      "2630  2745.4001  7902515829  139949792936.2800  -0.416584  \n",
      "2631  2733.9632  8098369688  140097189022.1300   1.366474  \n",
      "\n",
      "[2632 rows x 10 columns]\n",
      "logout success!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n    code：股票代码，sh或sz.+6位数字代码，或者指数代码，如：sh.601398。sh：上海；sz：深圳。此参数不可为空；\\n    fields：指示简称，支持多指标输入，以半角逗号分隔，填写内容作为返回类型的列。详细指标列表见历史行情指标参数章节。此参数不可为空；\\n    start：开始日期（包含），格式“YYYY-MM-DD”，为空时取2015-01-01；\\n    end：结束日期（不包含），格式“YYYY-MM-DD”，为空时取最近一个交易日；\\n    frequency：数据类型，默认为d，日k线；d=日k线、w=周、m=月、5=5分钟、15=15分钟、30=30分钟、60=60分钟k线数据，不区分大小写；指数没有分钟线数据；周线每周最后一个交易日才可以获取，月线第月最后一个交易日才可以获取。\\n参数名称 \\t参数描述 \\t说明\\ndate \\t交易所行情日期 \\t格式：YYYY-MM-DD\\ncode \\t证券代码 \\t格式：sh.600000。sh：上海，sz：深圳\\nopen \\t今开盘价格 \\t精度：小数点后4位；单位：人民币元\\nhigh \\t最高价 \\t精度：小数点后4位；单位：人民币元\\nlow \\t最低价 \\t精度：小数点后4位；单位：人民币元\\nclose \\t今收盘价 \\t精度：小数点后4位；单位：人民币元\\npreclose \\t昨日收盘价 \\t精度：小数点后4位；单位：人民币元\\nvolume \\t成交数量 \\t单位：股\\namount \\t成交金额 \\t精度：小数点后4位；单位：人民币元\\npctChg \\t涨跌幅 \\t精度：小数点后6位 \\n'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import baostock as bs\n",
    "import pandas as pd\n",
    "\n",
    "# 登陆系统\n",
    "lg = bs.login()\n",
    "# 显示登陆返回信息\n",
    "print('login respond error_code:'+lg.error_code)\n",
    "print('login respond  error_msg:'+lg.error_msg)\n",
    "\n",
    "# 获取指数(综合指数、规模指数、一级行业指数、二级行业指数、策略指数、成长指数、价值指数、主题指数)K线数据\n",
    "# 综合指数，例如：sh.000001 上证指数，sz.399106 深证综指 等；\n",
    "# 规模指数，例如：sh.000016 上证50，sh.000300 沪深300，sh.000905 中证500，sz.399001 深证成指,创业板 sz.399006等；\n",
    "# 一级行业指数，例如：sh.000037 上证医药，sz.399433 国证交运 等；\n",
    "# 二级行业指数，例如：sh.000952 300地产，sz.399951 300银行 等；\n",
    "# 策略指数，例如：sh.000050 50等权，sh.000982 500等权 等；\n",
    "# 成长指数，例如：sz.399376 小盘成长 等；\n",
    "# 价值指数，例如：sh.000029 180价值 等；\n",
    "# 主题指数，例如：sh.000015 红利指数，sh.000063 上证周期 等；\n",
    "\n",
    "\n",
    "# 详细指标参数，参见“历史行情指标参数”章节；“周月线”参数与“日线”参数不同。\n",
    "# 周月线指标：date,code,open,high,low,close,volume,amount,adjustflag,turn,pctChg\n",
    "rs = bs.query_history_k_data_plus(\"sz.399006\",\n",
    "    \"date,code,open,high,low,close,preclose,volume,amount,pctChg\",\n",
    "    start_date='2010-01-01', end_date='2021-03-30', frequency=\"d\")\n",
    "print('query_history_k_data_plus respond error_code:'+rs.error_code)\n",
    "print('query_history_k_data_plus respond  error_msg:'+rs.error_msg)\n",
    "\n",
    "# 打印结果集\n",
    "data_list = []\n",
    "while (rs.error_code == '0') & rs.next():\n",
    "    # 获取一条记录，将记录合并在一起\n",
    "    data_list.append(rs.get_row_data())\n",
    "result = pd.DataFrame(data_list, columns=rs.fields)\n",
    "# 结果集输出到csv文件\n",
    "result.to_csv(\".\\\\data\\\\history_Index_k_data.csv\", index=False)\n",
    "print(result)\n",
    "\n",
    "# 登出系统\n",
    "bs.logout()\n",
    "\n",
    "### 参数含义：\n",
    "'''\n",
    "    code：股票代码，sh或sz.+6位数字代码，或者指数代码，如：sh.601398。sh：上海；sz：深圳。此参数不可为空；\n",
    "    fields：指示简称，支持多指标输入，以半角逗号分隔，填写内容作为返回类型的列。详细指标列表见历史行情指标参数章节。此参数不可为空；\n",
    "    start：开始日期（包含），格式“YYYY-MM-DD”，为空时取2015-01-01；\n",
    "    end：结束日期（不包含），格式“YYYY-MM-DD”，为空时取最近一个交易日；\n",
    "    frequency：数据类型，默认为d，日k线；d=日k线、w=周、m=月、5=5分钟、15=15分钟、30=30分钟、60=60分钟k线数据，不区分大小写；指数没有分钟线数据；周线每周最后一个交易日才可以获取，月线第月最后一个交易日才可以获取。\n",
    "参数名称 \t参数描述 \t说明\n",
    "date \t交易所行情日期 \t格式：YYYY-MM-DD\n",
    "code \t证券代码 \t格式：sh.600000。sh：上海，sz：深圳\n",
    "open \t今开盘价格 \t精度：小数点后4位；单位：人民币元\n",
    "high \t最高价 \t精度：小数点后4位；单位：人民币元\n",
    "low \t最低价 \t精度：小数点后4位；单位：人民币元\n",
    "close \t今收盘价 \t精度：小数点后4位；单位：人民币元\n",
    "preclose \t昨日收盘价 \t精度：小数点后4位；单位：人民币元\n",
    "volume \t成交数量 \t单位：股\n",
    "amount \t成交金额 \t精度：小数点后4位；单位：人民币元\n",
    "pctChg \t涨跌幅 \t精度：小数点后6位 \n",
    "''' "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "971db267",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    },
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "本接口即将停止更新，请尽快使用Pro版接口：https://waditu.com/document/2\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "DatetimeIndex: 2275 entries, 2011-12-09 to 2021-04-21\n",
      "Data columns (total 6 columns):\n",
      " #   Column  Non-Null Count  Dtype  \n",
      "---  ------  --------------  -----  \n",
      " 0   open    2275 non-null   float64\n",
      " 1   close   2275 non-null   float64\n",
      " 2   high    2275 non-null   float64\n",
      " 3   low     2275 non-null   float64\n",
      " 4   volume  2275 non-null   float64\n",
      " 5   code    2275 non-null   int64  \n",
      "dtypes: float64(5), int64(1)\n",
      "memory usage: 124.4 KB\n",
      "None\n",
      "             open  close   high    low     volume    code\n",
      "date                                                     \n",
      "2011-12-09  0.795  0.797  0.814  0.795  1061772.0  159915\n",
      "2011-12-12  0.790  0.790  0.803  0.790   311065.0  159915\n",
      "2011-12-13  0.788  0.769  0.788  0.765   501994.0  159915\n",
      "2011-12-14  0.768  0.757  0.777  0.757   797671.0  159915\n",
      "2011-12-15  0.755  0.753  0.761  0.747   263174.0  159915\n",
      "...           ...    ...    ...    ...        ...     ...\n",
      "2021-04-15  2.695  2.698  2.698  2.663  2412531.0  159915\n",
      "2021-04-16  2.707  2.688  2.709  2.650  2438103.0  159915\n",
      "2021-04-19  2.681  2.798  2.799  2.672  3754710.0  159915\n",
      "2021-04-20  2.788  2.791  2.820  2.770  2918739.0  159915\n",
      "2021-04-21  2.767  2.814  2.818  2.767  2022147.0  159915\n",
      "\n",
      "[2275 rows x 6 columns]\n"
     ]
    }
   ],
   "source": [
    "import tushare as ts\n",
    "import pandas as pd\n",
    "\n",
    "# ts.set_token(3d369e6b9ec6f8dc82a475b0cd451a9187abe65f5f035b5bd0d9e18a)\n",
    "\n",
    "pro=ts.pro_api('3d369e6b9ec6f8dc82a475b0cd451a9187abe65f5f035b5bd0d9e18a')\n",
    "\n",
    "\n",
    "#1-需求一：使用tushare包获取某股票的历史行情数据。\n",
    "\n",
    "# 获取行情\n",
    "df = ts.get_k_data(code=\"159915\",start='2000-01-01')\n",
    "# 保存到本地\n",
    "df.to_csv('.\\\\data\\\\tushare_159915.csv')\n",
    "# 读取本地csv文件数据\n",
    "df = pd.read_csv('.\\\\data\\\\tushare_159915.csv')\n",
    "# 删除 Unnamed: 0 这一列，将 date 列转为时间类型，并设置为 index 列\n",
    "df.drop(labels='Unnamed: 0',axis=1,inplace=True)\n",
    "df['date'] = pd.to_datetime(df['date'])\n",
    "df.set_index('date',inplace=True)\n",
    "print(df.info())    # 查看整个数据集合中各个数据类型\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ccf8daee",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "module 'pandas' has no attribute 'rolling_mean'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-4-6828c1c2a99d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mma\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m20\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mdf\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'ma_'\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0mstr\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mma\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrolling_mean\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdf\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'close'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mma\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      3\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mto_csv\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'.\\\\data\\\\tushare1_159915.csv'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mFalse\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdrop\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlabels\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'Unnamed: 0'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0maxis\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0minplace\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'date'\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mpd\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mto_datetime\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdf\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'date'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mC:\\ProgramData\\Anaconda3\\envs\\py8\\lib\\site-packages\\pandas\\__init__.py\u001b[0m in \u001b[0;36m__getattr__\u001b[1;34m(name)\u001b[0m\n\u001b[0;32m    242\u001b[0m         \u001b[1;32mreturn\u001b[0m \u001b[0m_SparseArray\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    243\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 244\u001b[1;33m     \u001b[1;32mraise\u001b[0m \u001b[0mAttributeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34mf\"module 'pandas' has no attribute '{name}'\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    245\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    246\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mAttributeError\u001b[0m: module 'pandas' has no attribute 'rolling_mean'"
     ]
    }
   ],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py8",
   "language": "python",
   "name": "py8"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
